package com.dpiinc.TechPage.pen.activity

import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.os.SystemClock
import android.text.Editable
import android.text.SpannableString
import android.text.TextUtils
import android.text.TextWatcher
import android.text.style.ForegroundColorSpan
import android.util.DisplayMetrics
import android.util.Log
import android.util.SparseArray
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.EditText
import android.widget.TextView
import com.dpiinc.TechPage.BaseActivity
import com.dpiinc.TechPage.R
import com.dpiinc.TechPage.UserManager.getAccessToken
import com.dpiinc.TechPage.UserManager.getUserId
import com.dpiinc.TechPage.activity.EditNoteActivity
import com.dpiinc.TechPage.api.BaseObserver
import com.dpiinc.TechPage.api.RetrofitFactory
import com.dpiinc.TechPage.api.RxSchedulers
import com.dpiinc.TechPage.model.jbean.RecognizeGetBean
import com.dpiinc.TechPage.model.jbean.RecognizeUploadBean
import com.dpiinc.TechPage.room.RoomAiWriterDatabase
import com.dpiinc.TechPage.room.bean.RecognizeEntity
import com.dpiinc.TechPage.room.dao.RecognizeDao
import com.dpiinc.TechPage.user.utils.PermissionUtils
import com.dpiinc.TechPage.user.utils.ShareHelper
import com.dpiinc.TechPage.user.utils.ToastUtils
import com.dpiinc.TechPage.user.utils.ViewToBitmapUtil
import com.dpiinc.TechPage.utils.BaseTools
import com.dpiinc.TechPage.utils.DateUtils
import com.dpiinc.TechPage.widget.LoadingView
import com.beiji.lib.pen.cache.PenCacheManager.Companion.instance
import com.beiji.lib.pen.model.PenDot
import com.beiji.lib.pen.model.PenStroke
import com.beiji.lib.pen.ui.view.StrokeView
import com.yanzhenjie.permission.Action
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import java.io.*
import java.net.HttpURLConnection
import java.net.URL

/**
 * Created by hu489_000 on 2018-07-15.
 */
class HDRActivity() : BaseActivity() {
   // private val url = "http://hwrapi.tqltech.com/script"
    private val url = "https://hwrapi.pencloud.cn/script"
    private var key = "306d01c5-46d8-495a-9b72-edd9e0196c27"
    var hdr_result: EditText? = null
    var copybutton: TextView? = null
    var languageType = LANGUAGE_TYPE_CHINESES
    var mStrokeView: StrokeView? = null
    var noteId: String? = null
    var noteName: String? = null
    var dao: RecognizeDao? = null

    /**
     * s是否需要保存到数据库和服务器
     */
    var isNeedSave = false
    private var mSize = 0
    private var mReSize = 0
    private val bf = StringBuffer()
    private var mArr: SparseArray<ArrayList<PenStroke>>? = null
    private val mHandler: Handler = object : Handler() {
        @SuppressLint("HandlerLeak")
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            bf.append(msg.obj.toString() + "\n")
            Log.i(TAG, "handleMessage: mReSize=$mReSize,mSize=$mSize,bf=$bf")
            if (mReSize == mSize) {
                isNeedSave = true
                hdr_result!!.setText(bf.toString())
            } else {
                if (mArr?.size()!! > mReSize) {
                    strokeList.strokes = mArr!![mArr!!.keyAt(mReSize)]
                    startHandWritingRecognize()
                }
            }
        }
    }

    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        languageType =
            (if (("en" == resources.configuration.locale.language)) LANGUAGE_TYPE_ENGLISH else LANGUAGE_TYPE_CHINESES)
        setContentView(R.layout.hdr_main)
        super.onCreate(savedInstanceState)
        setBackWhite()
        setstatusBarColor(R.color.color_00bad2)
        hdr_result = findViewById<View>(R.id.hdr_result) as EditText
        noteId = intent.getStringExtra(ReplayActivity.ARG_NOTE_KEY)
        noteName = intent.getStringExtra(ARG_NEED_NAME)
        if (TextUtils.isEmpty(noteId)) {
            finish()
            return
        }
        val needReRecognize = intent.getBooleanExtra(ARG_NEED_RECOGNIZE, true)
        Log.i(TAG, "onCreate: $needReRecognize")
        dao = RoomAiWriterDatabase.getInstance(this@HDRActivity).recognizeDao()
        instance.loadCache(noteId!!, null)
        val noteCacheModel = instance.getCurrentCache()
        noteCacheModel?.readStrokesFromFile { penStrokes: ArrayList<PenStroke>? ->
            if (penStrokes == null || penStrokes.size < 1) {
                ToastUtils.showCenterTip(
                    this@HDRActivity,
                    getString(R.string.toast_replay_empty_stroke)
                )
                finish()
                return@readStrokesFromFile
            }
            if (needReRecognize) {
                handWritingRecognize()
            } else {
                recognize
            }
        }
        mStrokeView = findViewById<View>(R.id.stroke_view) as StrokeView
        mStrokeView!!.isDrawDotBg = false
        mStrokeView!!.loadCache(noteId!!)
        copybutton = findViewById<View>(R.id.copybutton) as TextView
        copybutton!!.setOnClickListener(object : View.OnClickListener {
            override fun onClick(view: View) {
                BaseTools.copy(hdr_result!!.text.toString())
            }
        })
    }

    /**
     * 分享功能
     */
    private fun showShare() {
        LoadingView.createLoadingViewAndShow(this, 0, null)
        instance.drainCache {
            val bitmapPathList: ArrayList<String> = instance.getPenStrokeBitmapPathList(noteId!!)
            setModifyTimeForShare()
            ViewToBitmapUtil.generateAllBitmap(this@HDRActivity, bitmapPathList)
            val textResult = hdr_result?.text.toString().trim()
            Log.e(TAG, "识别到的东西===>$textResult")
            if (TextUtils.isEmpty(textResult)) {
                ToastUtils.showCenterTip(this, getString(R.string.toast_replay_empty_stroke))
                LoadingView.dismissLoadingView()
                return@drainCache
            }
            instance.getCurrentCache()?.readStrokesFromFile {
                LoadingView.dismissLoadingView()
                if (it.isEmpty()) {
                    ToastUtils.showCenterTip(this, getString(R.string.toast_replay_empty_stroke))
                    LoadingView.dismissLoadingView()
                    return@readStrokesFromFile
                } else {
                    checkPermissionShowDialog(bitmapPathList,textResult)
                }
            }
        }
    }

    private fun checkPermissionShowDialog(bitmapPathList: ArrayList<String>, textResult: String) {
        val granted = Action<List<String>> {
            ShareHelper.showShareDialog(this@HDRActivity, bitmapPathList,textResult)
        }
        val denied = Action<List<String>> {
            ToastUtils.showTopTip(this@HDRActivity, getString(R.string.no_authority_share))
            Log.d(EditNoteActivity.TAG, "onAction denied")
        }
      //  if (PermissionUtils.checkWRITE_EXTERNAL_STORAGE(this@HDRActivity, granted, denied)) {
            ShareHelper.showShareDialog(this@HDRActivity, bitmapPathList,textResult)
    //    }
    }

    private fun setModifyTimeForShare() {
        ViewToBitmapUtil.setShareTime(DateUtils.getCurrentTimeMillis());
        ViewToBitmapUtil.setShareTitle(noteName)
    }

    /**
     * 这里先从数据库读取，没有的话，再从服务器拉，拉不到才用sdk识别。这段逻辑和leo沟通，先不用，直接从sdk获取
     */
    private val recognize: Unit
        private get() {
            val recognize = dao!!.getRecognizeByNoteId(noteId)
            if (recognize != null) {
                isNeedSave = false
                hdr_result!!.setText(recognize.recognizeResult)
            } else {
                recognizeGet(this, noteId)
            }
            hdr_result!!.addTextChangedListener(object : TextWatcher {
                override fun beforeTextChanged(
                    charSequence: CharSequence,
                    i: Int,
                    i1: Int,
                    i2: Int
                ) {
                }

                override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {
                    isNeedSave = true
                }

                override fun afterTextChanged(editable: Editable) {}
            })
        }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        // Inflate the menu; this adds items to the action bar if it is present.
        menuInflater.inflate(R.menu.menu_hdr_more, menu)
        val title =
            if (languageType == LANGUAGE_TYPE_CHINESES) getString(R.string.toolbar_chinese) else getString(
                R.string.toolbar_english
            )
        menu.getItem(0).title = title
        val item = menu.findItem(R.id.menu_more)
        val item2 = menu.findItem(R.id.hrd_share)

        val spannableString = SpannableString(item.title)
        spannableString.setSpan(
            ForegroundColorSpan(resources.getColor(R.color.clear_note_dialog_btn_text_color_left)),
            0,
            spannableString.length,
            0
        )
        item.title = spannableString
        return super.onCreateOptionsMenu(menu)
    }

    /**
     * 从sdk获取识别结果
     */
    private fun handWritingRecognize() {
        //这里为什么要重新附值呢。
//        isNeedSave = false;
//        ToastUtils.showTopTip(HDRActivity.this,getResources().getString(R.string.recognizing));
        val noteCacheModel = instance.getCurrentCache()
        noteCacheModel?.readStrokesFromFile { penStrokes: ArrayList<PenStroke>? ->
            if (penStrokes == null) {
                return@readStrokesFromFile
            }
            for (i in penStrokes.indices) {
                //Log.i(TAG, "invoke: " + penStrokes.get(i).toString());
            }
            strokeList.setStrokes(penStrokes)
            val list: ArrayList<Int> = ArrayList()
            for (stroke: PenStroke in strokeList.strokes!!) {
                if (!list.contains(stroke.page)) {
                    list.add(stroke.page)
                }
            }
            //处理分页上传
            mArr = SparseArray()
            Log.i(TAG, "invoke: mArr---" + list.size)
            if (list.size > 0) {
                for (integer: Int in list) {
                    val strokeList2: ArrayList<PenStroke> = ArrayList()
                    mArr!!.put(integer, strokeList2)
                    for (stroke: PenStroke in strokeList.strokes!!) {
                        if (stroke.page == integer) {
                            strokeList2.add(stroke)
                        }
                    }
                }
            }
            mSize = mArr!!.size()
            if (mSize > 0) {
                val keyAt: Int = mArr!!.keyAt(0)
                strokeList.strokes = mArr!!.get(keyAt)
                for (i in strokeList.strokes!!.indices) {
                    Log.i(TAG, "strokeList.strokes: " + strokeList.strokes!!.get(i))
                }
                startHandWritingRecognize()
            }
        }
    }

    private fun startHandWritingRecognize() {
        Thread(object : Runnable {
            override fun run() {
                try {
                    //先去从服务器获取key
                    val jsonObject = JSONObject()
                    jsonObject.put("cust", keyUser)
                    val keyData = requestService(keyUrl, jsonObject.toString())
                    key = getRecognitionResult(keyData)
                    Log.i(TAG, "run: $key")

                    //再去调用手写识别接口
                    val info = getJsonString(strokeList.strokes)
                    val value = requestService(url, info)
                    Log.i(TAG, "run: value=$value")
                    val jsonResult = JSONObject(value)
                    Log.i(TAG, "getRecognitionResult: $jsonResult")
                    val code = jsonResult.getInt("code")
                    val result = jsonResult.getString("data")
                    if (code == 0) {
                        mReSize++
                        val message = mHandler.obtainMessage()
                        message.what = mReSize
                        message.obj = result
                        mHandler.sendMessage(message)
                    } else {
                        Log.d(TAG, "ERROR_MESSAGE ERROR_MESSAGE = " + "识别错误")
                    }
                } catch (e: JSONException) {
                    e.printStackTrace()
                }
            }
        }).start()
    }

    var strokeList: StrokeList = StrokeList(this)

    //  当前页笔划类
    inner class StrokeList(private val mContext: Context) : Serializable {
        var strokes: ArrayList<PenStroke>? = null
        val pointStr: String
            get() {
                val sb = StringBuffer()
                for (k in strokes!!.indices) {
                    val s: PenStroke = strokes!![k]
                    if (s != null) {
                        val pointList: List<PenDot> = s.list
                        for (i in pointList.indices) {
                            sb.append((pointList[i].x) * 100).append(" ")
                                .append((pointList[i].y) * 100).append(",")
                        }
                        if (sb.length > 0) {
                            sb.deleteCharAt(sb.length - 1)
                            sb.append(";")
                        }
                    }
                }
                if (sb.length > 0) {
                    sb.deleteCharAt(sb.length - 1)
                }
                return sb.toString()
            }

        @JvmName("setStrokes1")
        fun setStrokes(strokes: ArrayList<PenStroke>) {
//            this.strokes = strokes;
            this.strokes = filterstrokes(strokes)
        }

        private fun filterstrokes(strokes: ArrayList<PenStroke>): ArrayList<PenStroke> {
            val eraserStrokes = ArrayList<PenStroke>()
            val penStrokes = ArrayList<PenStroke>()
            for (stroke: PenStroke in strokes) {
                if (stroke.action == PenStroke.ACTION_ERASER) {
                    Log.i(TAG, "filterstrokes:PenStroke.ACTION_ERASER ")
                    eraserStrokes.add(stroke)
                } else {
                    penStrokes.add(stroke)
                }
            }
            //橡皮擦数据的size
            val eraserSize = eraserStrokes.size
            //书写数据的size
            val penStrokeSize = penStrokes.size
            val screenDensity = screenDensity / 2
            Log.i(TAG, "filterstrokes:eraserSize= $eraserSize//penStrokeSize=$penStrokeSize")
            if (eraserSize > 0 && penStrokeSize > 0) {
                for (x in 0 until eraserSize) {
                    val eraserStroke = eraserStrokes[x]
                    val eraserDotList: List<PenDot> = eraserStroke.list
                    val listSize = eraserDotList.size
                    var i = 0
                    while (i < listSize) {
                        val eraserDot = eraserDotList[i]
                        val radius = eraserDot.f * screenDensity
                        for (y in 0 until penStrokeSize) {
                            var penStroke: PenStroke?
                            if (penStrokes.size <= y) {
                                penStroke = penStrokes[penStrokes.size-1]
                            } else {
                                penStroke = penStrokes[y]
                            }
                            if (eraserStroke.page != penStroke.page) {
                                //不在同一页就不用比较了
                                continue
                            }
                            if (eraserStroke.bookId != penStroke.bookId) {
                                //不是同一个本子也不用比较
                                continue
                            }
                            var shouldRemove = false
                            val strokeList: List<PenDot> = penStroke.list
                            val size = strokeList.size
                            if (size > 0) {
                                for (s in 0 until size) {
                                    val strokeDot = strokeList[s]
                                    val distance = getDistance(eraserDot, strokeDot).toDouble()
                                    if (Math.sqrt(distance) <= radius) {
                                        shouldRemove = true
                                        //只要一个stroke里有一个点在橡皮擦的区域内，整个stroke移除，后面的就没必要比较了
                                        break
                                    }
                                }
                            }
                            if (shouldRemove) {
                                penStrokes.remove(penStroke)
                            } else {
                                i++
                            }
                        }
                        i++
                    }
                }
                return penStrokes
            } else {
                return penStrokes
            }
        }

        private fun getDistance(eraserstroke: PenDot, stroke: PenDot): Int {
            return ((eraserstroke.x - stroke.x) * (eraserstroke.x - stroke.x) + (eraserstroke.y - stroke.y) * (eraserstroke.y - stroke.y)).toInt()
        }

        //屏幕分辨率容器
        private val screenDensity: Float
            private get() {
                val mDisplayMetrics = DisplayMetrics() //屏幕分辨率容器
                windowManager.defaultDisplay.getMetrics(mDisplayMetrics)
                return mDisplayMetrics.density
            }
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.menu_more -> return true
            R.id.hrd_share -> showShare()
            R.id.toolbar_chinese -> languageType = LANGUAGE_TYPE_CHINESES
            R.id.toolbar_english -> languageType = LANGUAGE_TYPE_ENGLISH
        }
        invalidateOptionsMenu()
        handWritingRecognize()
        return super.onOptionsItemSelected(item)
    }

    override fun onBackPressed() {
        if (isNeedSave) {
            var recognize = dao!!.getRecognizeByNoteId(noteId)
            if (recognize == null) {
                recognize = RecognizeEntity()
                recognize.setNoteId((noteId)!!)
                recognize.setLanguage(languageType.toString())
                recognize.setModifyTime(SystemClock.currentThreadTimeMillis())
                recognize.setNeedUpload(true)
                recognize.setRecognizeResult(hdr_result!!.text.toString())
                dao!!.insert(recognize)
            } else {
                recognize.language = languageType.toString()
                recognize.modifyTime = SystemClock.currentThreadTimeMillis()
                recognize.isNeedUpload = true
                recognize.recognizeResult = hdr_result!!.text.toString()
                dao!!.update(recognize)
            }
            recognizeUpload(this@HDRActivity, recognize)
        } else {
            super.onBackPressed()
        }
    }

    /**
     * 提交识别结果
     *
     * @param context
     */
    private fun recognizeUpload(context: Context, recognize: RecognizeEntity) {
//        ToastUtils.showTopTip(context,getResources().getString(R.string.recognize_result_saving));
        val requestMap = getRecognizeUploadMap(recognize)
        Log.i(TAG, "recognizeUpload: $requestMap")
        val observable = RetrofitFactory.getInstance().recognizeUpload(requestMap)
        val mBaseObserver: BaseObserver<RecognizeUploadBean> = object : BaseObserver<RecognizeUploadBean>(context) {
            override fun onHandleError(code: Int) {
                super.onHandleError(code)
                Log.d(TAG, "recognizeUpload onHandleError code = $code")
                finish()
            }

             override fun onHandleSuccess(baseBean: RecognizeUploadBean) {
                Log.d(TAG, "recognizeUpload onHandleSuccess RecognizeUploadBean = $baseBean")
                finish()
            }
        }
        observable.compose(RxSchedulers.compose()).subscribe(mBaseObserver);
    }

    private fun getRecognizeUploadMap(recognize: RecognizeEntity): HashMap<String, String> {
        val params = HashMap<String, String>()
        params["uId"] = getUserId()
        params["accessToken"] = getAccessToken()
        params["language"] = recognize.language
        params["noteId"] = recognize.noteId
        params["uploadTime"] = recognize.modifyTime.toString()
        params["recgData"] = recognize.recognizeResult
        return params
    }

    /**
     * 从服务器获取识别结果
     *
     * @param context
     */
    private fun recognizeGet(context: Context, noteId: String?) {
        val requestMap = getRecognizeGetMap(noteId)
        val observable = RetrofitFactory.getInstance().recognizeGet(requestMap)
        val mBaseObserver: BaseObserver<RecognizeGetBean> = object : BaseObserver<RecognizeGetBean>(context) {
            override fun onHandleError(code: Int) {
                super.onHandleError(code)
                Log.d(TAG, "recognizeGet onHandleError code = $code")
                handWritingRecognize()
            }

             override fun onHandleSuccess(baseBean: RecognizeGetBean?) {
                Log.d(TAG, "recognizeGet onHandleSuccess RecognizeUploadBean = $baseBean")
                if (baseBean != null && TextUtils.isEmpty(baseBean.recgData)) {
                    handWritingRecognize()
                    return
                }
                var recognize = dao!!.getRecognizeByNoteId(noteId)
                if (recognize == null) {
                    recognize = RecognizeEntity()
                    recognize.setNoteId((noteId)!!)
                    recognize.setLanguage(baseBean!!.language)
                    recognize.setModifyTime(java.lang.Long.getLong(baseBean.recgTime))
                    recognize.setNeedUpload(false)
                    recognize.setRecognizeResult(baseBean.recgData)
                    dao!!.insert(recognize)
                } else {
                    recognize.language = baseBean!!.language
                    recognize.modifyTime = java.lang.Long.getLong(baseBean.recgTime)
                    recognize.isNeedUpload = false
                    recognize.recognizeResult = baseBean.recgData
                    dao!!.update(recognize)
                }
                hdr_result!!.setText(baseBean.recgData)
                isNeedSave = false
            }
        }
        observable.compose(RxSchedulers.compose()).subscribe(mBaseObserver);
       // observable.compose(RxSchedulers.compose<Any>()).subscribe(mBaseObserver)
    }

    private fun getRecognizeGetMap(noteId: String?): HashMap<String, String?> {
        val params = HashMap<String, String?>()
        params["uId"] = getUserId()
        params["accessToken"] = getAccessToken()
        params["noteId"] = noteId
        params["localRecgTime"] = ""
        return params
    }

    fun requestService(urlValue: String?, keyValue: String?): String {
        var out: OutputStream? = null
        var br: BufferedReader? = null
        var msg = ""
        if (keyValue != null && keyValue != "") {
            try {
                val url = URL(urlValue)
                Log.i(TAG, "requestService: $url")
                val httpURLConnection = url.openConnection() as HttpURLConnection
                httpURLConnection.requestMethod = "POST"
                // 设置通用的请求属性
                httpURLConnection.setRequestProperty("accept", "*/*")
                httpURLConnection.setRequestProperty("Content-Type", "application/json")
                httpURLConnection.setRequestProperty("charset", "utf-8")
                httpURLConnection.useCaches = false
                httpURLConnection.doInput = true
                httpURLConnection.doOutput = true
                out = httpURLConnection.outputStream
                val buf = keyValue.toString().toByteArray()
                out.write(buf)
                val code = httpURLConnection.responseCode
                if (code == HttpURLConnection.HTTP_OK) {
                    val `in` = httpURLConnection.inputStream
                    val isr = InputStreamReader(`in`)
                    br = BufferedReader(isr)
                    var tmp = ""
                    while ((br.readLine().also { tmp = it }) != null) {
                        msg += tmp
                    }
                    Log.i(TAG, "onSuccess: $msg")
                } else {
                    Log.i(TAG, "onFailure: $code")
                }
            } catch (e: Exception) {
                e.printStackTrace()
            } finally {
                try {
                    out?.close()
                    br?.close()
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        }
        return msg
    }

    fun getRecognitionResult(value: String?): String {
        var result = ""
        if (value != null && value.trim { it <= ' ' } != "") {
            try {
                val jsonObject = JSONObject(value)
                Log.i(TAG, "getRecognitionResult: $jsonObject")
                val code = jsonObject.getInt("code")
                result = jsonObject.getString("data")
            } catch (e: JSONException) {
                e.printStackTrace()
            }
        }
        return result
    }

    private fun getJsonString(list: ArrayList<PenStroke>?): String {
        val json = JSONObject()
        try {
            json.put("viewSizeHeight", 1900)
            json.put("viewSizeWidth", 2300)
            json.put("applicationKey", "306d01c5-46d8-495a-9b72-edd9e0196c27")
            json.put("scriptType", "Text")
            //json.put("scriptType","Math");
            //中英文类型选择
            if (LANGUAGE_TYPE_CHINESES == languageType) {
                json.put("languages", "zh_CN")
            } else if (LANGUAGE_TYPE_ENGLISH == languageType) {
                json.put("languages", "en")
            } else {
                json.put("languages", "zh_CN")
            }
            json.put("xDPI", 35)
            json.put("yDPI", 35)
            val jsonArray = JSONArray()
            if (list != null && list.size > 0) {
                var jsonPoint: JSONObject? = null
                var xValue: String = ""
                var yValue: String = ""
                for (penStroke: PenStroke in list) {
                    val dotList: List<PenDot> = penStroke.list
                    Log.i(TAG, "getJsonString: " + dotList.size)
                    for (i in dotList.indices) {
                        if (i == 0) {
                            jsonPoint = JSONObject()
                            xValue += dotList[i].x
                            yValue += dotList[i].y
                        } else if (i > 0 && i < (dotList.size - 1)) {
                            xValue += "," + dotList[i].x
                            yValue += "," + dotList[i].y
                        } else if (i == dotList.size - 1) {
                            xValue += "," + dotList[i].x
                            yValue += "," + dotList[i].y
                            jsonPoint!!.put("x", xValue)
                            jsonPoint.put("y", yValue)
                            jsonArray.put(jsonPoint)
                            xValue = ""
                            yValue = ""
                        }
                    }
                }
            }
            json.put("penData", jsonArray)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        Log.i(TAG, "getJsonString: $json")
        //BLEFileUtil.writeTxtToFile(json.toString(), "/mnt/sdcard/tql/", "test.txt");
        return json.toString()
    }

    companion object {
        val APPLICATION_KEY = "a55a66c9-ae8f-482e-bb90-c2771390d388"
        val APPLICATION_ID = "com.wenba.ocr.demo"
       // private val keyUrl = "http://hwrapi.tqltech.com/script"
        private val keyUrl = "https://hwrapi.pencloud.cn/script"
        private val keyUser = "AIwrite"
        var LANGUAGE_TYPE_CHINESES = 2
        var LANGUAGE_TYPE_ENGLISH = 3
        val SUCCESS_MESSAGE = 1
        val ERROR_MESSAGE = 2
        val SUCCESS_FLAG = "success"
        val ARG_NEED_RECOGNIZE = "need_recognize"
        val ARG_NEED_NAME = "need_name"
        private val TAG = "HDRActivity"
    }
}